<template>
  <div class="p-6">
    <a-card>
      <!-- 搜索和操作栏 -->
      <div class="mb-4 flex justify-between">
        <a-space>
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索应用名称/ID"
            style="width: 200px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="channelType"
            style="width: 120px"
            placeholder="支付渠道"
            @change="handleSearch"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="alipay">支付宝</a-select-option>
            <a-select-option value="wechat">微信支付</a-select-option>
          </a-select>
        </a-space>
        <a-button type="primary" @click="handleAdd">
          <template #icon><plus-outlined /></template>
          新建应用
        </a-button>
      </div>

      <!-- 应用列表 -->
      <a-table
        :columns="columns"
        :data-source="appList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <!-- 应用名称 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="flex items-center">
              <img :src="record.icon" class="w-8 h-8 mr-2 rounded" />
              <div>
                <div class="font-medium">{{ record.name }}</div>
                <div class="text-gray-500 text-sm">ID: {{ record.appId }}</div>
              </div>
            </div>
          </template>

          <!-- 支付渠道 -->
          <template v-if="column.key === 'channel'">
            <a-tag :color="record.channel === 'alipay' ? 'blue' : 'green'">
              {{ record.channel === 'alipay' ? '支付宝' : '微信支付' }}
            </a-tag>
          </template>

          <!-- 状态 -->
          <template v-if="column.key === 'status'">
            <a-badge
              :status="record.status === 'active' ? 'success' : 'error'"
              :text="record.status === 'active' ? '已启用' : '已禁用'"
            />
          </template>

          <!-- 操作 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个应用吗？"
                @confirm="handleDelete(record)"
              >
                <a class="text-red-500">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新建/编辑应用弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalType === 'add' ? '新建应用' : '编辑应用'"
      @ok="handleModalOk"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="应用名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入应用名称" />
        </a-form-item>
        <a-form-item label="支付渠道" name="channel">
          <a-select v-model:value="formData.channel" placeholder="请选择支付渠道">
            <a-select-option value="alipay">支付宝</a-select-option>
            <a-select-option value="wechat">微信支付</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="应用图标" name="icon">
          <a-upload
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            :max-count="1"
          >
            <a-button>
              <upload-outlined /> 上传图标
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item label="应用描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入应用描述"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, UploadOutlined } from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'

// 表格列定义
const columns = [
  {
    title: '应用名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '支付渠道',
    dataIndex: 'channel',
    key: 'channel',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
]

// 测试数据
const appList = ref([
  {
    id: 1,
    name: '支付宝小程序',
    appId: '2021000000000001',
    channel: 'alipay',
    icon: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
    status: 'active',
    createTime: '2024-01-01 12:00:00',
    description: '支付宝小程序支付应用',
  },
  {
    id: 2,
    name: '微信小程序',
    appId: 'wx123456789',
    channel: 'wechat',
    icon: 'https://res.wx.qq.com/a/wx_fed/assets/res/OTE0YTAw.png',
    status: 'active',
    createTime: '2024-01-02 12:00:00',
    description: '微信小程序支付应用',
  },
  {
    id: 3,
    name: '支付宝H5',
    appId: '2021000000000002',
    channel: 'alipay',
    icon: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
    status: 'inactive',
    createTime: '2024-01-03 12:00:00',
    description: '支付宝H5支付应用',
  },
])

// 搜索和筛选
const searchText = ref('')
const channelType = ref('')
const loading = ref(false)

// 分页
const pagination = ref<TablePaginationConfig>({
  total: 3,
  current: 1,
  pageSize: 10,
})

// 弹窗相关
const modalVisible = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const formRef = ref()
const formData = ref({
  name: '',
  channel: undefined,
  icon: '',
  description: '',
})
const fileList = ref([])

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入应用名称' }],
  channel: [{ required: true, message: '请选择支付渠道' }],
}

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索:', searchText.value, channelType.value)
}

// 表格变化
const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.value = pag
  // TODO: 实现分页逻辑
}

// 新建应用
const handleAdd = () => {
  modalType.value = 'add'
  formData.value = {
    name: '',
    channel: undefined,
    icon: '',
    description: '',
  }
  modalVisible.value = true
}

// 编辑应用
const handleEdit = (record: any) => {
  modalType.value = 'edit'
  formData.value = { ...record }
  modalVisible.value = true
}

// 删除应用
const handleDelete = (record: any) => {
  // TODO: 实现删除逻辑
  message.success('删除成功')
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！')
  }
  return isImage && isLt2M
}

// 弹窗确认
const handleModalOk = () => {
  formRef.value?.validate().then(() => {
    // TODO: 实现保存逻辑
    message.success(modalType.value === 'add' ? '创建成功' : '更新成功')
    modalVisible.value = false
  })
}

onMounted(() => {
  // TODO: 加载数据
})
</script>

<style scoped>
.ant-upload-list-picture-card .ant-upload-list-item {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
}
</style>